package com.intelligentmeterreadingsys.waterlist.copywater.activity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.NoticeVo;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.report.activity.ReportNoRFIDActivity;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;

import dbhelper.XmlNameHelper;

/**
 * RFID异常抄表
 * 
 * @author king
 * 
 */
public class CopyWaterNoRFIDActivity extends Activity implements OnClickListener {
    public static final int REQUEST_CODE_TAKE_IMAGE = 1;// 回调函数标志
    public RelativeLayout layout = null;
    public Button button4;// 拍照
    public Button button5;// 保存
    public Button button6;// 上传
    public EditText edit2;// 本次刻度
    public EditText edit3;// 备注
    public TextView textview1;// 水表编号
    public TextView textview2;// 水表地址
    public TextView textview3;// 用水量
    public TextView textview4;// 上次抄表刻度
    public TextView textview5;// 用水性质
    public TextView textview6;// 口径
    public TextView textview7;// 用户姓名
    public TextView textview8;// 电话
    public TextView info;// 提示信息
    public String waterid;
    public boolean isupload = false;
    public static final int ITEM0 = Menu.FIRST;// 系统值

    private final static int DIALOG = 1;

    public List<UserWaterVO> list = null;

    public boolean isSave = false;
    public int i = 0;

    public ProgressDialog pd;
    public SharedPreferenceUtil sh = null;
    public String message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.copywater_norfid);
	sh = new SharedPreferenceUtil(this);
	init();
    }

    /**
     * 初始化控件
     */
    public void init() {
	button4 = (Button) findViewById(R.id.copywater_norfid_paizhao);
	button5 = (Button) findViewById(R.id.copywater_norfid_save);
	button6 = (Button) findViewById(R.id.copywater_norfid_upload);
	button4.setOnClickListener(this);
	button5.setOnClickListener(this);
	button6.setOnClickListener(this);
	edit2 = (EditText) findViewById(R.id.copywater_norfid_thismonthwater);
	edit2.addTextChangedListener(new TextWatcher() {

	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {

	    }

	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	    }

	    @Override
	    public void afterTextChanged(Editable s) {
		if (list != null && list.size() > 0) {
		    if (list.get(i) != null && !TextUtils.isEmpty(s.toString())) {
			Double thisusewater = Double.parseDouble(s.toString()) - list.get(i).getLastmonthwater();

			textview3.setText(thisusewater + "");
			System.out.println("上限" + list.get(i).getAlarmlimit() + "下限" + list.get(i).getLowalarmlimit());
			if (list.get(i).getAlarmlimit() == 0.0) {
			    textview3.setTextColor(Color.BLACK);
			} else {
			    if (thisusewater > list.get(i).getAlarmlimit() || thisusewater < list.get(i).getLowalarmlimit()) {
				textview3.setTextColor(Color.RED);
			    } else {
				textview3.setTextColor(Color.BLACK);
			    }
			}

		    } else {
			textview3.setText("");
		    }
		}

	    }
	});

	edit3 = (EditText) findViewById(R.id.copywater_norfid_desc);
	textview1 = (TextView) findViewById(R.id.copywater_norfid_waternumber);
	textview2 = (TextView) findViewById(R.id.copywater_norfid_wateradds);
	textview3 = (TextView) findViewById(R.id.copywater_norfid_usewater);
	textview4 = (TextView) findViewById(R.id.copywater_norfid_lastmonthwater);
	textview5 = (TextView) findViewById(R.id.copywater_norfid_waterproperties);
	textview6 = (TextView) findViewById(R.id.copywater_norfid_metercaliber);
	textview7 = (TextView) findViewById(R.id.copywater_norfid_username);
	textview8 = (TextView) findViewById(R.id.copywater_norfid_phone);
	info = (TextView) findViewById(R.id.copywater_norfid_textView1);
	info.isEnabled();

	layout = (RelativeLayout) findViewById(R.id.copywater_norfid_relativelayout);

	waterid = getIntent().getStringExtra("waterid");
	if (!TextUtils.isEmpty(waterid)) {
	    CopyWaterDao dao = new CopyWaterDao(this);
	    this.list = dao.queryUserWaterInfo(null, null, waterid);
	    sh.insertValue(XmlNameHelper.QUERYWATERLIST, list.get(0).getWaterlistId());
	    NoticeInfo(list.get(0));
	    dao.close();
	    viewDate();
	}

    }

    /**
     * 展现数据
     */
    public void viewDate() {
	textview1.setText("");
	textview2.setText("");
	textview3.setText("");
	textview4.setText("");
	textview5.setText("");
	textview6.setText("");
	textview7.setText("");
	textview8.setText("");
	edit2.setText("");
	edit3.setText("");
	if (list != null && list.size() > 0) {
	    UserWaterVO water = list.get(0);
	    textview1.setText(list.get(i).getWaternumber());
	    textview2.setText(list.get(i).getAdds());
	    textview4.setText(list.get(i).getLastmonthwater() + "");
	    textview5.setText(water.getWaterproperties());
	    textview6.setText(water.getMetercaliber());
	    textview7.setText(water.getName());
	    textview8.setText(water.getPhone());
	    edit3.setText(list.get(i).getDesc());
	    if (list.get(i).getThismonthwater() > 0) {
		edit2.setText(list.get(i).getThismonthwater() + "");
		textview3.setText("" + (list.get(i).getThismonthwater() - list.get(i).getLastmonthwater()));
	    }
	}
    }

    /**
     * 翻页
     */
    public void filp() {
	if (i < 0) {
	    i = 0;
	    Toast.makeText(CopyWaterNoRFIDActivity.this, "没有前面的数据了！", Toast.LENGTH_LONG).show();
	} else if (i > (list.size() - 1)) {
	    i = list.size() - 1;
	    Toast.makeText(CopyWaterNoRFIDActivity.this, "没有后面的数据了！", Toast.LENGTH_LONG).show();
	} else {
	    viewDate();
	}
    }

    @Override
    public void onClick(View v) {
	if (v.getId() == button4.getId()) {
	    System.out.println("拍照");
	    Intent intent = new Intent(CopyWaterNoRFIDActivity.this, ImageSwitcherActivity.class);

	    Bundle bundle = new Bundle();
	    if (list == null || list.size() < 1) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "没有水表不能拍照", 1000).show();
		return;
	    }
	    bundle.putString("otherid", list.get(i).getWaterid());
	    bundle.putString("status", "2");
	    bundle.putString("classname", "CopyWaterNoRFIDActivity");
	    intent.putExtras(bundle);
	    startActivity(intent);

	} else if (button5.getId() == v.getId()) {
	    if (list == null || list.size() < 1) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "没有水表不能保存！", 1000).show();
		return;
	    }
	    if (TextUtils.isEmpty(edit2.getEditableText().toString())) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "你还没有抄表呢！", 1000).show();
		return;
	    }
	    if (isupload || list.get(0).getIsupload().equals("1")) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了，不能修改", 1000).show();
		return;
	    }
	    boolean b = save();
	    if (b) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "抄表成功!", 1000).show();
		isSave = true;
	    } else {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "保存失败!", 1000).show();
		isSave = false;
	    }

	} else if (button6.getId() == v.getId()) {
	    if (isupload) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了", 1000).show();
		return;
	    }
	    if (!isSave) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "请保存后再上传！", 1000).show();
		return;
	    }
	    if (list.get(i).getIsupload().equals("1")) {
		Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了", 1000).show();
		return;
	    }
	    pd = new ProgressDialog(CopyWaterNoRFIDActivity.this);
	    pd.setMessage("上传中......");
	    pd.show();
	    CopyWaterDao dao = new CopyWaterDao(CopyWaterNoRFIDActivity.this);

	    final WaterInfoVO water = dao.queryOneNoUpload(null, list.get(i).getWaterid(), "0");
	    dao.close();
	    new Thread() {

		@Override
		public void run() {

		    Map<String, String> map = new HashMap<String, String>();

		    Map<File, String> mapfile = new HashMap<File, String>();
		    Map<String, String> map1 = new HashMap<String, String>();
		    map1.put("waternumber", water.getWaternumber());
		    map1.put("usewater", water.getThismonthwater() - water.getLastmonthwater() + "");
		    map1.put("imsi", sh.getValue(XmlNameHelper.IMSI));
		    map1.put("thismonthwater", water.getThismonthwater() + "");
		    map1.put("thisdate", water.getThisdate());
		    map1.put("desc", water.getDesc());
		    map1.put("sid", "0");
		    map1.put("isnorfid", water.getIsNorfid());
		    List<String> list = water.getImagepath();
		    for (int k = 0; k < list.size(); k++) {
			File file = new File(list.get(k));
			if (file.exists()) {
			    mapfile.put(file, "imagepath");
			    map.put(file.getName(), "imagename");
			}
		    }
		    RequestUrl re = new RequestUrl(CopyWaterNoRFIDActivity.this);
		    String respon = UploadHttpClient.uploadSubmit(re.getUrl(RequestUrl.COPYWATERLIST), map, mapfile, map1);
		    if (respon.equals("error")) {
			Message msg = myHandler.obtainMessage();
			msg.what = 1;
			myHandler.sendMessage(msg);
		    } else {
			try {
			    JSONObject json = new JSONObject(respon);
			    String message = json.getString("message");
			    if (message.equals("yes")) {
				Message msg = myHandler.obtainMessage();
				msg.what = 2;
				myHandler.sendMessage(msg);
			    } else {
				Message msg = myHandler.obtainMessage();
				msg.what = 3;
				myHandler.sendMessage(msg);
			    }
			} catch (JSONException e) {

			    Message msg = myHandler.obtainMessage();
			    msg.what = 3;
			    myHandler.sendMessage(msg);
			}

		    }

		}

	    }.start();
	}
    }

    /**
     * 保存抄表数据
     * 
     * @return
     */
    public boolean save() {
	boolean b = false;
	if (list.get(0).getIsupload().equals("1")) {
	    Toast.makeText(CopyWaterNoRFIDActivity.this, "已经上传过了不能再抄", 1000).show();
	    return false;
	}
	CopyWaterDao dao = new CopyWaterDao(this);
	b = dao.isPhotograph(list.get(0).getWaterid());
	dao.close();
	if (!b) {
	    Toast.makeText(CopyWaterNoRFIDActivity.this, "你还没拍照呢", 1000).show();
	    return false;
	}
	CopyWaterDao daos = new CopyWaterDao(this);
	b = daos.saveWater(list.get(i).getWaterid(), Double.parseDouble(edit2.getEditableText().toString()), edit3.getEditableText().toString(), "1");
	this.list = daos.queryUserWaterInfo(null, null, list.get(0).getWaterid());
	daos.close();
	viewDate();
	return b;

    }

    /**
     * 上传消息处理
     */
    Handler myHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {

	    if (msg.what == 2) {
		pd.dismiss();
		Toast.makeText(CopyWaterNoRFIDActivity.this, "上传成功", 1000).show();
		CopyWaterDao dao = new CopyWaterDao(CopyWaterNoRFIDActivity.this);
		dao.uploadstatus(list.get(i).getWaterid());
		dao.queryUserWaterInfo(null, null, waterid);
		dao.close();
		isupload = true;

	    } else {
		pd.dismiss();
		Toast.makeText(CopyWaterNoRFIDActivity.this, "上传失败", 1000).show();
		isupload = false;
	    }
	    super.handleMessage(msg);
	}

    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	menu.add(0, ITEM0, 0, "RFID异常报案");
	menu.add(0, ITEM0 + 1, 0, "发短息");
	menu.add(0, ITEM0 + 2, 0, "打电话");
	menu.findItem(ITEM0 + 1);

	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

	if (list == null && list.size() < 1) {
	    Toast.makeText(CopyWaterNoRFIDActivity.this, "没有水表不能进行此操作", 1000).show();
	    return false;
	}
	switch (item.getItemId()) {
	case ITEM0:
	    if (list != null && list.size() > 0) {
		Intent intent = new Intent(CopyWaterNoRFIDActivity.this, ReportNoRFIDActivity.class);
		intent.putExtra("waterid", list.get(0).getWaterid());
		startActivity(intent);
	    }

	    break;
	case ITEM0 + 1:
	    if (list != null && list.size() > 0) {

		Uri smsToUri = Uri.parse("smsto:");
		String userwater = textview3.getText().toString();
		Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
		sendIntent.putExtra("address", list.get(0).getPhone()); // 电话号码，这行去掉的话，默认就没有电话
		sendIntent.putExtra("sms_body", "尊敬的" + list.get(0).getName() + "用户:你本月用水量为:" + userwater);
		sendIntent.setType("vnd.android-dir/mms-sms");
		startActivity(sendIntent);
	    }
	    break;
	case ITEM0 + 2:
	    Intent intent = new Intent();
	    intent.setAction("Android.intent.action.CALL");
	    intent.setData(Uri.parse("tel:" + list.get(0).getPhone()));// mobile为你要拨打的电话号码，模拟器中为模拟器编号也可
	    startActivity(intent);
	    break;
	default:
	    break;
	}
	return super.onOptionsItemSelected(item);
    }

    // 查询提示信息
    public void NoticeInfo(UserWaterVO water) {
	CopyWaterDao dao = new CopyWaterDao(this);
	WaterInfoVO wa = new WaterInfoVO();
	wa.setGroupingname(water.getGroupingname());
	wa.setWaterlistid(water.getWaterlistId());
	wa.setGroupingsort(water.getGroupingsort());
	wa.setGroupwatersort(water.getGroupwatersort());
	System.out.println("组名：" + wa.getGroupingname() + "----组顺序" + wa.getGroupingsort() + "---表顺序" + wa.getGroupwatersort() + "------表册ID" + wa.getWaterlistid() + "----水表ID"
		+ water.getWaterid());
	NoticeVo na = dao.queryNotice(wa);
	dao.close();
	info.setText("本组数:" + na.getThisGroup() + "    未抄数:" + na.getThisNoCopy());
	if (na.getLastWaterlistNoCopy() > 0) {
	    message = "警告！你在" + na.getListwaterlistName() + "表册还有" + na.getLastWaterlistNoCopy() + "个水表未抄";
	    showDialog(DIALOG);

	}
	if (na.getLastNoCopy() > 0) {
	    message = "警告！你在" + na.getLastgroupName() + "组还有" + na.getLastNoCopy() + "个水表未抄,应抄水表:" + na.getLastWaterAdds();

	    showDialog(DIALOG);
	}

	if (na.getThisNoCopy() > 1) {
	    if (!na.getNextWaterid().equals(water.getWaterid())) {
		Toast.makeText(this, "抄表顺序有误！应抄" + na.getNextwateradds(), Toast.LENGTH_LONG).show();
	    }
	} else {
	    Toast.makeText(this, "这已是本组最后一个了", Toast.LENGTH_LONG).show();
	}

    }

    @Override
    protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {

	case DIALOG:
	    Builder builder = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder.setMessage(message);

	    // 添加一个确定按钮
	    builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder.create();
	    break;

	default:
	    break;
	}

	return dialog;
    }

}
